<template>
  <div @click="handleDownload">
    <slot :loading="loading" :disabled="disabled" />
  </div>
</template>

<script setup>
import { downLoad } from '@/api/api'
import { watch, computed, ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
const exportUrl = {
  diningRecord: '/api/diningRecord/export', // 餐厅就餐记录
  BAList: '/pension-organization-approves/overall/export', // 备案信息查询
  orgBaseInfosList: '/pension-organizations/information/export', // 机构基本信息
  exportPersonnel: '/personnel/export', // 从业人员导出
  exportJgAqgl:'/security/jg-export',
  exportXFZG:'/fire/jg-export', // 消防安全整改
  exportQTZG:'/security/jg-export', // 其他安全整改
  fireList:'/fire/list-export', // 机构端消防安全导出
  fireJdList:'/fire/jg-export', // 监管端消防安全导出
  homeOrganizationExport: '/homeOrganization/export', // 信息查询----社区养老服务机构
  areaElderServiceCenterExport: '/area-elder-service-center/export', // 信息查询----区域养老服务中心
  fundStatisticExport: '/fund-statistic/export', // 资金使用情况
  fundItemListExport: '/fund-item/list-export', // 养老项目库导出 市区
  fundItem_jgExport: '/fund-item/jg-export', // 养老项目库导出 省
  orgList: '/pension-organizations/information/export', // 机构档案信息
  studentBMListExport :'/students/gov-export',//学员报名列表导出
  studentDA :'/students/export',//学员档案导出
  trainOrg :'/trainingOrganization/download-template',//培训机构导出
  trainRecordManage :'/trainingRecords/download-template',//培训记录导出
  exportZHTJ :'/center-analysis/comprehensive/export',//综合统计导出
  exportZHCX :'/center-analysis/search-list/export',//综合查询导出
  exportXXJL :'/students/study/export',//学习记录导出
  exportKSJL :'/exam-result/list/export',//考试记录导出
}

const props = defineProps({
  url: {
    type: String,
    default() {
      return ''
    }
  },
  params: {
    type: Object,
    default() {
      return {}
    }
  },
  fileName: {
    type: String,
    default: '导出数据'
  },
  fileType: {
    type: String,
    default: ''
  },
  disabled: {
    type: Boolean,
    default: false
  },
  api:{
    type: String,
    default: '/biz'
  }
})

const loading = ref(false)

/**
 * @description: get 参数拼接
 * @param {type}
 * @return:
 */

const encodeSearchParams = obj => {
  const params = []

  Object.keys(obj).forEach(key => {
    let value = obj[key]

    if (typeof value === 'undefined' || value == '') {
      value = ''
    }
    params.push([key, encodeURIComponent(value)].join('='))
  })
  return params.join('&')
}

const downloadExcel = async () => {
  loading.value = true
  // const apiUrl = exportUrl[props.url] + '?'
  // const url = apiUrl + encodeSearchParams(props.params)
  const apiUrl = exportUrl[props.url]
  debugger
  const res = await downLoad(props.params, apiUrl, props.api)
  if (res instanceof Blob) {
    blobToText(res)
      .then(result => {
        ElMessage.error(result.msg)
      })
      .catch(() => {
        startDownload(res)
      })
  }
  loading.value = false
}

// blob对象转json 判断错误信息
const blobToText = blob => {
  return new Promise((resolve, reject) => {
    const fileReader = new FileReader()
    fileReader.readAsText(blob)
    fileReader.onload = function (ev) {
      try {
        const result = JSON.parse(ev.target.result)
        if (result && result.succeed == false) {
          resolve(result)
        } else {
          reject()
        }
      } catch (e) {
        // TODO handle the exception
        reject()
      }
    }
  })
}

// 开始处理下载
const startDownload = res => {
  const blob = new Blob([res], {
    type: res.type
  })
  const fileName = props.fileName
  if (window.navigator.msSaveOrOpenBlob) {
    navigator.msSaveBlob(blob, fileName)
  } else {
    var link = document.createElement('a')
    link.href = window.URL.createObjectURL(blob)
    link.download = fileName
    link.click()
    // 释放内存
    window.URL.revokeObjectURL(link.href)
  }
}

const downloadWord = async () => {
  loading.value = true
  // const apiUrl = exportUrl[props.url] + '?'
  // const url = apiUrl + encodeSearchParams(props.params)
  const apiUrl = exportUrl[props.url]
  const res = await downLoad(props.params, apiUrl, props.api)
  if (res instanceof Blob) {
    const blob = new Blob([res], {
      type: res.type
    })
    const fileName = props.fileName + '.doc'
    if (window.navigator.msSaveOrOpenBlob) {
      navigator.msSaveBlob(blob, fileName)
    } else {
      var link = document.createElement('a')
      link.href = window.URL.createObjectURL(blob)
      link.download = fileName
      link.click()
      // 释放内存
      window.URL.revokeObjectURL(link.href)
    }
  }
  loading.value = false
}

const downloadZip = async () => {
  loading.value = true
  // const apiUrl = exportUrl[props.url] + '?'
  // const url = apiUrl + encodeSearchParams(props.params)
  if (res instanceof Blob) {
    const apiUrl = exportUrl[props.url]
    const res = await downLoad(props.params, apiUrl, props.api)

    const blob = new Blob([res], { type: 'application/zip' })
    const fileName = props.fileName + '.zip'
    if ('download' in document.createElement('a')) {
      // 非IE下载
      const elink = document.createElement('a')
      elink.download = fileName
      elink.style.display = 'none'
      elink.href = window.URL.createObjectURL(blob)
      document.body.appendChild(elink)
      elink.click()
      window.URL.revokeObjectURL(elink.href) // 释放URL 对象
      document.body.removeChild(elink)
    } else {
      // IE10+下载
      navigator.msSaveBlob(blob, fileName)
    }
  }
  loading.value = false
}

const handleDownload = () => {
  if (props.disabled) {
    return
  }
  console.log(props.fileType)
  if (props.fileType === 'zip') {
    downloadZip()
  } else if (props.fileType === 'doc') {
    downloadWord()
  } else {
    downloadExcel()
  }
}
</script>

<style scoped lang="scss"></style>
